package com.example.admin.mybledemo.ota;

import android.bluetooth.BluetoothGattCharacteristic;
import cn.com.heaton.blelibrary.ble.BleLog;

import com.example.admin.mybledemo.BleRssiDevice;
import com.example.admin.mybledemo.OtaManager;
import com.example.admin.mybledemo.ota.OtaConfig;
import com.example.admin.mybledemo.ota.ProtocolVersion;

import java.util.List;
import java.util.ArrayList;

import cn.com.heaton.blelibrary.ble.BleLog;
import cn.com.heaton.blelibrary.ble.model.BleDevice;

public class OtaStateMachine {

    private static final String TAG = "OtaStateMachine";

    private OtaManager.OtaProgressListener progressListener;
    private BleCommunicator bleCommunicator;
    private FirmwareParser firmwareParser;
    private StateMachineCallback stateMachineCallback;

    private OtaConfig config;
    private OtaManager.RetryState retryState;

    private BleRssiDevice targetDevice;
    private BleRssiDevice phase2Device;
    private ProtocolVersion detectedVersion = ProtocolVersion.V1;

    private OtaState currentState = OtaState.IDLE;
    private List<OtaBlock> otaBlocks;
    private int currentBlockIndex = 0;

    private String deviceVersion = "";
    private String deviceRomVersion = "";
    private String targetVersion = "";
    private String creditCode = "";
    private String macAddress = "";

    // 第二阶段传输状态
    private Phase2DataManager phase2DataManager;

    // 添加Boot模式设备扫描器
    private BootDeviceScanner bootDeviceScanner;



    public interface StateMachineCallback {
        void scheduleConnectRetry(Runnable retryAction);
        void scheduleVersionCheckRetry(Runnable retryAction);
        void scheduleCredentialCheckRetry(Runnable retryAction);
        void scheduleDataTransferRetry(Runnable retryAction);
        void scheduleVerificationRetry(Runnable retryAction);
        void scheduleNextBlock(Runnable nextBlockAction);
        void onStateChanged(OtaState state);
        void onProgressChanged(int progress, int total);
        void onError(int errorCode, String errorMessage);
        void onSuccess();
        void onLog(String message);
        void onVersionInfo(String deviceVersion, String romVersion, String targetVersion);
        void onProtocolDetected(ProtocolVersion version);
    }

    public OtaStateMachine(StateMachineCallback stateMachineCallback,
                           BleCommunicator bleCommunicator,
                           FirmwareParser firmwareParser,
                           OtaConfig config,
                           OtaManager.RetryState retryState) {
        this.stateMachineCallback = stateMachineCallback;
        this.bleCommunicator = bleCommunicator;
        this.firmwareParser = firmwareParser;
        this.config = config;
        this.retryState = retryState;
        
        // 初始化Boot模式设备扫描器
        this.bootDeviceScanner = new BootDeviceScanner();
        this.bootDeviceScanner.setScanListener(new BootDeviceScanner.BootDeviceScanListener() {
            @Override
            public void onBootDeviceFound(BleRssiDevice device) {
                if (stateMachineCallback != null) {
                    stateMachineCallback.onLog("✓ 自动发现Boot模式设备: " + device.getBleName() + " (" + device.getBleAddress() + ")");
                }
                // 自动连接Boot模式设备
                targetDevice = device;
                changeState(OtaState.PHASE2_CONNECTING);
                bleCommunicator.connect(device);
            }
            
            @Override
            public void onScanFailed(String errorMessage) {
                if (stateMachineCallback != null) {
                    stateMachineCallback.onLog("✗ Boot模式设备扫描失败: " + errorMessage);
                }
            }
            
            @Override
            public void onScanTimeout() {
                if (stateMachineCallback != null) {
                    stateMachineCallback.onLog("✗ Boot模式设备扫描超时，请手动扫描并连接Boot模式设备");
                }
            }
            
            @Override
            public void onScanStatusUpdate(String message) {
                if (stateMachineCallback != null) {
                    stateMachineCallback.onLog("Boot扫描状态: " + message);
                }
            }
        });
    }

    public void setProgressListener(OtaManager.OtaProgressListener listener) {
        this.progressListener = listener;
    }

    public void setConfig(OtaConfig config) {
        this.config = config;
    }

    public void startOta(BleRssiDevice device, List<OtaBlock> otaBlocks, String creditCode, String macAddress) {
        this.targetDevice = device;
        this.otaBlocks = otaBlocks;
        this.creditCode = creditCode;
        this.macAddress = macAddress;
        this.currentBlockIndex = 0;
        this.retryState.reset();

        changeState(OtaState.PHASE1_CONNECTING);
        bleCommunicator.connect(targetDevice);
    }

    public void stopOta() {
        changeState(OtaState.CANCELLED);
        if (targetDevice != null) {
            bleCommunicator.disconnect(targetDevice);
        }
        
        // 停止Boot模式设备扫描
        if (bootDeviceScanner != null) {
            bootDeviceScanner.stopScan();
        }
        
        if (stateMachineCallback != null) {
            stateMachineCallback.onError(OtaConstants.ASK_STATE_UNKNOW, "OTA升级已取消");
        }
    }

    public boolean isInProgress() {
        return currentState.isInProgress();
    }

    public OtaState getCurrentState() {
        return currentState;
    }

    public int getCurrentProgress() {
        return currentBlockIndex;
    }

    public String getDeviceVersion() {
        return deviceVersion;
    }

    public String getDeviceRomVersion() {
        return deviceRomVersion;
    }

    public String getTargetVersion() {
        return targetVersion;
    }

    public ProtocolVersion getDetectedVersion() {
        return detectedVersion;
    }

    // BLE Event handlers
    public void onConnected(BleDevice device) {
        BleLog.d(TAG, "onConnected called, current state: " + currentState);
        if (stateMachineCallback != null) {
            stateMachineCallback.onLog("OtaStateMachine.onConnected 被调用，当前状态: " + currentState);
        }
        
        if (currentState == OtaState.PHASE1_CONNECTING) {
            changeState(OtaState.PHASE1_DISCOVERING_SERVICES);
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("已连接到设备，等待服务发现以确定设备模式...");
                stateMachineCallback.onLog("状态已更新为: PHASE1_DISCOVERING_SERVICES");
            }
            
            // 等待服务发现来确定设备是APP模式还是Boot模式
            
        } else if (currentState == OtaState.PHASE1_DEVICE_RESTART) {
            // 设备重启后重新连接，检查是否为Boot模式
            changeState(OtaState.PHASE2_BOOT_MODE);
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("设备重启后重新连接，检查Boot模式...");
            }
        } else if (currentState == OtaState.PHASE2_CONNECTING) {
            changeState(OtaState.PHASE2_BOOT_MODE);
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("Boot模式设备连接成功，状态已更新为: PHASE2_BOOT_MODE");
            }
            // 重要：连接成功后重置重试计数器（与Flutter端保持一致）
            retryState.connectRetryCount = 0;
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("Boot模式设备连接成功，重置重试计数器");
            }
        } else if (currentState == OtaState.PHASE2_SCANNING_BOOT_DEVICE) {
            changeState(OtaState.PHASE2_BOOT_MODE);
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("状态已更新为: PHASE2_BOOT_MODE");
            }
        } else {
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("onConnected: 状态不匹配，当前状态: " + currentState);
            }
        }
    }

    public void onDisconnected(BleDevice device) {
        // **关键修改：如果是升级命令阶段，立即切换状态阻止重连**
        if (currentState == OtaState.PHASE1_UPGRADE_CMD) {
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("升级命令阶段设备断开连接，切换到重启状态阻止自动重连");
            }
            
            // 立即切换状态，阻止任何重连尝试
            changeState(OtaState.PHASE1_DEVICE_RESTART);
            
            // 强制禁用自动重连
            forceDisableAutoConnect(device);
            
            // 开始扫描Boot模式设备
            startScanForBootDevice();
            return;
        }
        
        if (currentState == OtaState.PHASE1_DEVICE_RESTART || currentState == OtaState.PHASE2_BOOT_MODE) {
            // 设备重启后断开连接是正常的，不需要重试连接原设备
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("设备重启断开连接，等待Boot模式设备重新连接...");
            }
            
            // 强制禁用自动重连
            forceDisableAutoConnect(device);
            return;
        }
        
        if (currentState != OtaState.COMPLETED && currentState != OtaState.CANCELLED && currentState != OtaState.FAILED) {
            stateMachineCallback.scheduleConnectRetry(() -> bleCommunicator.connect(device));
        }
    }

    public void onConnectFailed(BleDevice device, int errorCode) {
        // 添加调试日志
        if (stateMachineCallback != null) {
            stateMachineCallback.onLog("OtaStateMachine.onConnectFailed 被调用，当前状态: " + currentState + ", 设备: " + device.getBleName() + ", 错误码: " + errorCode);
        }
        
        if (currentState == OtaState.PHASE1_DEVICE_RESTART) {
            // 设备重启过程中连接失败是正常的，不需要重试连接原设备
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("设备重启过程中连接失败（错误码:" + errorCode + "），继续等待Boot模式设备...");
            }
            return;
        }
        
        if (currentState == OtaState.PHASE2_BOOT_MODE || currentState == OtaState.PHASE2_CONNECTING) {
            // Boot模式设备连接失败，需要重试
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("Boot模式设备连接失败（错误码:" + errorCode + "），准备重试...");
            }
            
            // 检查是否是连接超时（错误码2034）
            if (errorCode == 2034) {
                if (stateMachineCallback != null) {
                    stateMachineCallback.onLog("Boot模式设备连接超时，这是正常现象，设备可能还在重启中...");
                }
            }
            
            // 延迟重试连接Boot模式设备（与Flutter端保持一致：8秒超时后重试）
            stateMachineCallback.scheduleConnectRetry(() -> {
                if (stateMachineCallback != null) {
                    stateMachineCallback.onLog("重试连接Boot模式设备: " + device.getBleName());
                }
                bleCommunicator.connect(device);
            });
            return;
        }
        
        if (currentState != OtaState.COMPLETED && currentState != OtaState.CANCELLED && currentState != OtaState.FAILED) {
            stateMachineCallback.scheduleConnectRetry(() -> bleCommunicator.connect(device));
        }
    }

    public void onServicesDiscovered(BleDevice device) {
        BleLog.d(TAG, "onServicesDiscovered called, current state: " + currentState + ", device: " + device.getBleName());
        if (stateMachineCallback != null) {
            stateMachineCallback.onLog("OtaStateMachine.onServicesDiscovered 被调用，当前状态: " + currentState + ", 设备: " + device.getBleName());
        }
        
        // 修复状态处理：如果当前状态是PHASE1_CONNECTING，说明onServicesDiscovered比onConnected先调用
        // 这种情况下直接转换到PHASE1_DISCOVERING_SERVICES状态
        if (currentState == OtaState.PHASE1_CONNECTING) {
            changeState(OtaState.PHASE1_DISCOVERING_SERVICES);
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("修正状态：从CONNECTING转换到DISCOVERING_SERVICES");
            }
        }
        
        // 处理第一阶段的服务发现
        if (currentState == OtaState.PHASE1_DISCOVERING_SERVICES || currentState == OtaState.PHASE1_ROM_CHECK) {
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("服务发现完成，检测设备模式...");
            }
            
            // 检测设备当前处于什么模式
            boolean isBootMode = isBootModeDevice((BleRssiDevice) device);
            BleLog.d(TAG, "Device mode detection result: " + (isBootMode ? "Boot Mode" : "APP Mode"));
            
            if (isBootMode) {
                // 设备已处于Boot模式，直接开始第二阶段数据传输
                if (stateMachineCallback != null) {
                    stateMachineCallback.onLog("检测到Boot模式设备，直接开始第二阶段数据传输");
                }
                targetDevice = (BleRssiDevice) device; // 更新目标设备为Boot模式设备
                startDataTransfer();
            } else {
                // 设备处于APP模式，检测协议版本并进行版本检查
                detectProtocolVersion();
                if (stateMachineCallback != null) {
                    stateMachineCallback.onLog("检测到APP模式设备，协议版本: " + detectedVersion + "，开始版本检查");
                }
                performVersionCheck();
            }
        } else if (currentState == OtaState.PHASE2_BOOT_MODE) {
            // 设备重启后重新连接，检查是否为Boot模式
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("服务发现完成，检查是否为Boot模式设备...");
            }
            
            // 检查是否有Boot模式的服务UUID
            boolean hasBootService = checkForBootModeService(device);
            
            if (hasBootService) {
                // 设备已处于Boot模式，开始第二阶段数据传输
                if (stateMachineCallback != null) {
                    stateMachineCallback.onLog("检测到Boot模式服务，开始第二阶段数据传输");
                }
                targetDevice = (BleRssiDevice) device; // 更新目标设备为Boot模式设备
                startDataTransfer();
            } else {
                // 设备仍然处于APP模式，可能需要更多时间重启
                if (stateMachineCallback != null) {
                    stateMachineCallback.onLog("设备仍然处于APP模式，继续等待重启...");
                }
                // 断开连接，等待设备完全重启
                bleCommunicator.disconnect(device);
            }
        } else if (currentState == OtaState.PHASE2_CONNECTING) {
            startDataTransfer();
        } else {
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("onServicesDiscovered: 状态不匹配，当前状态: " + currentState);
            }
        }
    }
    
    /**
     * 检测设备是否处于Boot模式
     * 与Flutter端保持一致：检查设备名称是否为"ble_ota"或MAC地址匹配随机MAC
     */
    private boolean isBootModeDevice(BleRssiDevice device) {
        try {
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("检查设备是否为Boot模式...");
            }
            
            String deviceName = device.getBleName();
            String deviceMac = device.getBleAddress();
            String randomMac = RandomMacManager.getInstance().getRandomMacString();
            
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("设备名称: " + deviceName);
                stateMachineCallback.onLog("设备MAC: " + deviceMac);
                stateMachineCallback.onLog("随机MAC: " + randomMac);
            }
            
            // 方法1：检查设备名称是否为"ble_ota"或MAC地址匹配随机MAC（Flutter端逻辑）
            boolean nameMatches = "ble_ota".equals(deviceName);
            boolean macMatches = !randomMac.isEmpty() && 
                               deviceMac.toUpperCase().equals(randomMac.toUpperCase());
            
            // 方法2：检查设备名称是否包含"ble_ota"（兼容更多设备名称格式）
            boolean nameContainsBoot = deviceName != null && deviceName.toLowerCase().contains("ble_ota");
            
            // 方法3：检查设备名称是否以"ble_ota"开头（兼容"ble_ota_v22"等格式）
            boolean nameStartsWithBoot = deviceName != null && deviceName.toLowerCase().startsWith("ble_ota");
            
            // 方法4：检查设备名称是否以"ble_ota_v"开头（兼容"ble_ota_v22"等格式）
            boolean nameStartsWithBootV = deviceName != null && deviceName.toLowerCase().startsWith("ble_ota_v");
            
            boolean isBootMode = nameMatches || macMatches || nameContainsBoot || nameStartsWithBoot || nameStartsWithBootV;
            
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("名称匹配(ble_ota): " + nameMatches);
                stateMachineCallback.onLog("名称包含(ble_ota): " + nameContainsBoot);
                stateMachineCallback.onLog("名称开头(ble_ota): " + nameStartsWithBoot);
                stateMachineCallback.onLog("名称开头(ble_ota_v): " + nameStartsWithBootV);
                stateMachineCallback.onLog("MAC地址匹配: " + macMatches);
                if (isBootMode) {
                    stateMachineCallback.onLog("✓ 检测到Boot模式设备！");
                } else {
                    stateMachineCallback.onLog("✗ 仍为APP模式设备");
                }
            }
            
            return isBootMode;
        } catch (Exception e) {
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("Boot模式检测异常: " + e.getMessage());
            }
            return false;
        }
    }
    
    /**
     * 检查设备是否有Boot模式的服务
     * 与Flutter端保持一致：检查设备名称是否为"ble_ota"或MAC地址匹配随机MAC
     */
    private boolean checkForBootModeService(BleDevice device) {
        try {
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("重连后检查设备是否为Boot模式...");
            }
            
            String deviceName = device.getBleName();
            String deviceMac = device.getBleAddress();
            String randomMac = RandomMacManager.getInstance().getRandomMacString();
            
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("重连设备名称: " + deviceName);
                stateMachineCallback.onLog("重连设备MAC: " + deviceMac);
                stateMachineCallback.onLog("期望随机MAC: " + randomMac);
            }
            
            // Flutter端逻辑：检查设备名称是否为"ble_ota"或MAC地址匹配随机MAC
            boolean nameMatches = "ble_ota".equals(deviceName);
            boolean macMatches = !randomMac.isEmpty() && 
                               deviceMac.toUpperCase().equals(randomMac.toUpperCase());
            
            boolean hasBootService = nameMatches || macMatches;
            
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("重连名称匹配(ble_ota): " + nameMatches);
                stateMachineCallback.onLog("重连MAC地址匹配: " + macMatches);
                if (hasBootService) {
                    stateMachineCallback.onLog("✓ 重连后检测到Boot模式设备！");
                } else {
                    stateMachineCallback.onLog("✗ 重连后仍为APP模式设备，继续等待...");
                }
            }
            
            return hasBootService;
        } catch (Exception e) {
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("Boot模式服务检测异常: " + e.getMessage());
            }
            return false;
        }
    }
    


    public void onCharacteristicRead(BleDevice device, BluetoothGattCharacteristic characteristic) {
        // 添加BleLog确保即使stateMachineCallback为null也能看到调用
        BleLog.d(TAG, "OtaStateMachine.onCharacteristicRead 被调用，当前状态: " + currentState + ", 特征值: " + characteristic.getUuid());
        
        if (stateMachineCallback != null) {
            stateMachineCallback.onLog("onCharacteristicRead被调用，当前状态: " + currentState + ", 特征值: " + characteristic.getUuid());
        } else {
            BleLog.e(TAG, "OtaStateMachine.onCharacteristicRead: stateMachineCallback 为 null!");
        }
        
        // 启用版本检查读取回调
        if (currentState == OtaState.PHASE1_VERSION_CHECK) {
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("状态匹配，开始处理版本数据");
            }
            BleLog.d(TAG, "状态匹配，开始处理版本数据");
            onVersionDataReceived(characteristic.getValue());
        } else {
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("状态不匹配，当前状态: " + currentState + ", 期望状态: PHASE1_VERSION_CHECK");
            }
            BleLog.w(TAG, "状态不匹配，当前状态: " + currentState + ", 期望状态: PHASE1_VERSION_CHECK");
        }
    }

    public void onCharacteristicWrite(BleDevice device, BluetoothGattCharacteristic characteristic) {
        if (stateMachineCallback != null) {
            stateMachineCallback.onLog("onCharacteristicWrite called");
            stateMachineCallback.onLog("Current state: " + currentState);
            stateMachineCallback.onLog("Device address: " + device.getBleAddress());
        }
        
        if (currentState == OtaState.PHASE1_CREDENTIAL_CHECK) {
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("凭证数据写入成功，等待设备响应...");
            }
            // 设置超时，如果设备在5秒内没有响应，直接发送升级命令
            stateMachineCallback.scheduleCredentialCheckRetry(new Runnable() {
                @Override
                public void run() {
                    if (currentState == OtaState.PHASE1_CREDENTIAL_CHECK) {
                        if (stateMachineCallback != null) {
                            stateMachineCallback.onLog("设备响应超时，直接发送升级命令");
                        }
                        sendUpdateCommand();
                    }
                }
            });
        } else if (currentState == OtaState.PHASE1_UPGRADE_CMD) {
            // 升级命令写入成功，设备将重启
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("升级命令写入成功，设备将重启到Boot模式...");
            }
            
            // 立即禁用自动重连，在设备断开之前！
            try {
                cn.com.heaton.blelibrary.ble.Ble.getInstance().autoConnect(targetDevice, false);
                if (stateMachineCallback != null) {
                    stateMachineCallback.onLog("升级命令成功后立即禁用自动重连");
                }
            } catch (Exception e) {
                if (stateMachineCallback != null) {
                    stateMachineCallback.onLog("禁用自动重连失败: " + e.getMessage());
                }
            }
            
            // 检查是否是V2协议（V2协议可以直接开始第二阶段）
            if (detectedVersion == ProtocolVersion.V2) {
                // V2版本直接开始第二阶段
                if (stateMachineCallback != null) {
                    stateMachineCallback.onLog("V2协议：直接开始第二阶段数据传输...");
                }
                startDataTransfer();
            } else {
                // V1版本需要等待设备重启并重连
                changeState(OtaState.PHASE1_DEVICE_RESTART);
                if (stateMachineCallback != null) {
                    stateMachineCallback.onLog("V1协议：等待设备重启并进入Boot模式...");
                }
                
                // 重要：禁用原设备的自动重连，防止BLE库自动重连原设备
                try {
                    cn.com.heaton.blelibrary.ble.Ble.getInstance().autoConnect(targetDevice, false);
                    if (stateMachineCallback != null) {
                        stateMachineCallback.onLog("已禁用原设备的自动重连");
                    }
                } catch (Exception e) {
                    if (stateMachineCallback != null) {
                        stateMachineCallback.onLog("禁用自动重连时出错: " + e.getMessage());
                    }
                }
                
                // 保存设备信息，等待重连
                phase2Device = targetDevice;
                
                // 断开连接，等待设备重启，然后扫描Boot模式设备
                bleCommunicator.disconnect(targetDevice);
                
                // 开始扫描Boot模式设备
                startScanForBootDevice();
            }
        } else if (currentState == OtaState.PHASE2_DATA_TRANSFER) {
            // 第二阶段写入成功，转发给Phase2DataManager处理
            if (phase2DataManager != null) {
                // 获取写入的数据（从characteristic中获取）
                byte[] writtenData = characteristic.getValue();
                if (writtenData == null) {
                    writtenData = new byte[0];
                }
                phase2DataManager.onWriteSuccess(writtenData);
            }
        } else if (currentState == OtaState.PHASE2_BOOT_MODE) {
            // Boot模式下发送第二阶段开始命令成功
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("✅ Boot模式设备连接成功，开始第二阶段数据传输");
            }
            startDataTransfer();
        } else if (currentState == OtaState.PHASE2_VERIFICATION) {
            // 结束命令写入成功，直接完成OTA（参考Flutter实现）
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("=== 结束命令写入成功 ===");
                stateMachineCallback.onLog("参考Flutter实现，直接完成OTA");
                stateMachineCallback.onLog("所有数据写入完成");
            }
            completeOta();
        } else {
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("未知状态: " + currentState);
            }
        }
    }
    
    public void onWriteFailed(BleDevice device, int errorCode) {
        if (stateMachineCallback != null) {
            stateMachineCallback.onLog("写入失败，错误码: " + errorCode);
        }
        
        // 根据当前状态处理写入失败
        if (currentState == OtaState.PHASE1_CREDENTIAL_CHECK) {
            stateMachineCallback.onError(OtaConstants.ASK_STATE_FAIL_CODE, "凭证验证写入失败，错误码: " + errorCode);
        } else if (currentState == OtaState.PHASE1_UPGRADE_CMD) {
            // 升级命令写入失败，可能是设备重启导致的
            if (errorCode == 133 || errorCode == 2032) {
                if (stateMachineCallback != null) {
                    stateMachineCallback.onLog("升级命令写入后设备重启，这是正常行为，等待设备重新连接...");
                }
                
                // 重要：设置状态为设备重启，这样onDisconnected和onConnectFailed就不会重试连接原设备
                changeState(OtaState.PHASE1_DEVICE_RESTART);
                
                // 检查是否是V2协议（V2协议可以直接开始第二阶段）
                if (detectedVersion == ProtocolVersion.V2) {
                    // V2版本直接开始第二阶段
                    if (stateMachineCallback != null) {
                        stateMachineCallback.onLog("V2协议：直接开始第二阶段数据传输...");
                    }
                    startDataTransfer();
                } else {
                    // V1版本需要等待设备重启并重连
                    if (stateMachineCallback != null) {
                        stateMachineCallback.onLog("V1协议：等待设备重启并进入Boot模式...");
                    }
                    
                    // 重要：禁用原设备的自动重连，防止BLE库自动重连原设备
                    try {
                        cn.com.heaton.blelibrary.ble.Ble.getInstance().autoConnect(targetDevice, false);
                        if (stateMachineCallback != null) {
                            stateMachineCallback.onLog("已禁用原设备的自动重连，防止干扰Boot模式设备连接");
                        }
                    } catch (Exception e) {
                        if (stateMachineCallback != null) {
                            stateMachineCallback.onLog("禁用自动重连时出错: " + e.getMessage());
                        }
                    }
                    
                    // 保存设备信息，等待重连
                    phase2Device = targetDevice;
                    
                    // 开始扫描Boot模式设备
                    startScanForBootDevice();
                }
            } else {
                stateMachineCallback.onError(OtaConstants.ASK_STATE_UNKNOW, "升级命令写入失败，错误码: " + errorCode);
            }
        } else if (currentState == OtaState.PHASE2_DATA_TRANSFER) {
            stateMachineCallback.onError(OtaConstants.ASK_STATE_UNKNOW, "数据传输写入失败，错误码: " + errorCode);
        } else if (currentState == OtaState.PHASE2_VERIFICATION) {
            stateMachineCallback.onError(OtaConstants.ASK_STATE_UNKNOW, "验证写入失败，错误码: " + errorCode);
        }
    }
    
    /**
     * 处理第一阶段设备通知
     */
    private void handlePhase1Notification(byte[] response) {
        if (response.length == 0) {
            return;
        }
        
        int responseCode = response[0];
        if (stateMachineCallback != null) {
            stateMachineCallback.onLog("第一阶段响应码: " + responseCode);
        }
        
        switch (responseCode) {
            case 0:
                if (stateMachineCallback != null) {
                    stateMachineCallback.onLog("凭证验证成功，发送升级命令");
                }
                sendUpdateCommand();
                break;
            case 1:
                stateMachineCallback.onError(OtaConstants.ASK_STATE_FAIL_MAC, "写入随机地址不合法");
                break;
            case 2:
                stateMachineCallback.onError(OtaConstants.ASK_STATE_FAIL_CODE, "mac code认证失败");
                break;
            default:
                stateMachineCallback.onError(OtaConstants.ASK_STATE_UNKNOW, "未知错误码: " + responseCode);
        }
    }
    
    /**
     * 处理第二阶段设备通知
     * 与Flutter端保持一致：只在收到错误码时处理，成功情况下不处理
     */
    private void handlePhase2Notification(byte[] response) {
        if (response.length == 0) {
            return;
        }
        
        int responseCode = response[0];
        if (stateMachineCallback != null) {
            stateMachineCallback.onLog("第二阶段响应码: " + responseCode);
        }
        
        // 与Flutter端保持一致：只在收到错误码时处理
        switch (responseCode) {
            case 1:
                stateMachineCallback.onError(OtaConstants.ASK_STATE_UNKNOW, "升级过程中收到未知命令");
                break;
            case 2:
                stateMachineCallback.onError(OtaConstants.ASK_STATE_UNKNOW, "收到不是预期的包类型");
                break;
            case 3:
                stateMachineCallback.onError(OtaConstants.ASK_STATE_UNKNOW, "FCS校验失败");
                break;
            case 4:
                stateMachineCallback.onError(OtaConstants.ASK_STATE_UNKNOW, "非法地址");
                break;
            case 5:
                stateMachineCallback.onError(OtaConstants.ASK_STATE_UNKNOW, "Credit Code不合法");
                break;
            default:
                // 与Flutter端保持一致：成功情况下不处理通知
                // 第二阶段的数据传输逻辑由Phase2DataManager通过写入成功回调处理
                if (stateMachineCallback != null) {
                    stateMachineCallback.onLog("第二阶段成功响应，继续数据传输");
                }
                break;
        }
    }
    
    /**
     * 处理第二阶段结束通知
     */
    private void handlePhase2EndNotification(byte[] response) {
        if (stateMachineCallback != null) {
            stateMachineCallback.onLog("=== handlePhase2EndNotification called ===");
            stateMachineCallback.onLog("Response length: " + response.length);
            stateMachineCallback.onLog("Response data: " + bytesToHexString(response));
            stateMachineCallback.onLog("Current state: " + currentState);
            stateMachineCallback.onLog("第二阶段传输完成！");
        }
        completeOta();
    }
    
    

    public void onCharacteristicChanged(BleDevice device, BluetoothGattCharacteristic characteristic) {
        // Handle notifications from device
        byte[] response = characteristic.getValue();
        
        if (stateMachineCallback != null) {
            String hexData = bytesToHexString(response);
            stateMachineCallback.onLog("=== onCharacteristicChanged called ===");
            stateMachineCallback.onLog("Response data: " + hexData);
            stateMachineCallback.onLog("Current state: " + currentState);
            stateMachineCallback.onLog("Characteristic UUID: " + characteristic.getUuid());
        }
        
        // Check if OTA is in progress (similar to Flutter's _otaing check)
        if (!isInProgress()) {
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("OTA not in progress, ignoring notification");
            }
            return;
        }
        
        // Check if response is empty
        if (response == null || response.length == 0) {
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("Received empty notification, ignoring");
            }
            return;
        }
        
        // Handle notification based on current state
        if (currentState == OtaState.PHASE1_CREDENTIAL_CHECK) {
            handlePhase1Notification(response);
        } else if (currentState == OtaState.PHASE2_DATA_TRANSFER || currentState == OtaState.PHASE2_BOOT_MODE) {
            // 第二阶段通知处理：只在收到错误码时处理
            handlePhase2Notification(response);
        } else if (currentState == OtaState.PHASE2_VERIFICATION) {
            handlePhase2EndNotification(response);
        } else {
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("Current state does not support notification handling: " + currentState);
            }
        }
    }
    
    private String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X", b));
        }
        return sb.toString();
    }

    public void onDescriptorWriteSuccess(BleDevice device, android.bluetooth.BluetoothGattDescriptor descriptor) {
        if (stateMachineCallback != null) {
            stateMachineCallback.onLog("通知描述符写入成功");
        }
    }

    public void onMtuChanged(BleDevice device, int mtu, int status) {
        // Handle MTU change confirmation
    }

    public void onReadRemoteRssi(BleDevice device, int rssi, int status) {
        // Handle RSSI read
    }

    private void changeState(OtaState newState) {
        currentState = newState;
        if (stateMachineCallback != null) {
            stateMachineCallback.onStateChanged(newState);
        }
        if (progressListener != null) {
            progressListener.onLog("State changed to: " + newState.getDescription());
        }
    }

    private void detectProtocolVersion() {
        // 目前默认使用V1协议（从日志看设备是V1版本）
        // TODO: 后续可以通过服务UUID检测协议版本
        detectedVersion = ProtocolVersion.V1;
        if (stateMachineCallback != null) {
            stateMachineCallback.onLog("使用V1协议，需要等待设备重启");
            stateMachineCallback.onProtocolDetected(detectedVersion);
        }
    }

    private void performVersionCheck() {
        changeState(OtaState.PHASE1_VERSION_CHECK);
        if (stateMachineCallback != null) {
            stateMachineCallback.onLog("开始版本校验...");
            stateMachineCallback.onLog("状态已更新为: PHASE1_VERSION_CHECK");
            stateMachineCallback.onLog("准备读取特征值: " + OtaProtocol.APP_OTA_VERSION_UID);
        }
        bleCommunicator.readCharacteristic(targetDevice, OtaProtocol.APP_OTA_SERVICE_UID, OtaProtocol.APP_OTA_VERSION_UID);
    }

    private void onVersionDataReceived(byte[] versionData) {
        // 添加BleLog确保即使stateMachineCallback为null也能看到调用
        BleLog.d(TAG, "onVersionDataReceived 被调用，数据长度: " + versionData.length);
        
        try {
            // 添加详细的调试日志
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("收到版本数据，原始长度: " + versionData.length);
                StringBuilder hexString = new StringBuilder();
                StringBuilder asciiString = new StringBuilder();
                for (int i = 0; i < versionData.length; i++) {
                    hexString.append(String.format("%02X ", versionData[i]));
                    char c = (char) (versionData[i] & 0xFF);
                    asciiString.append(Character.isISOControl(c) ? '.' : c);
                }
                stateMachineCallback.onLog("版本数据(HEX): " + hexString.toString());
                stateMachineCallback.onLog("版本数据(ASCII): " + asciiString.toString());
            } else {
                BleLog.e(TAG, "onVersionDataReceived: stateMachineCallback 为 null!");
                // 即使callback为null，也要输出数据信息
                StringBuilder hexString = new StringBuilder();
                for (int i = 0; i < versionData.length; i++) {
                    hexString.append(String.format("%02X ", versionData[i]));
                }
                BleLog.d(TAG, "版本数据(HEX): " + hexString.toString());
            }
            
            // 解析设备版本信息（与Flutter端保持一致）
            // 1. 字节序转换：将4字节数据按小端序转换
            // 2. 前2字节是ROM版本，后2字节是软件版本
            if (versionData.length >= 4) {
                BleLog.d(TAG, "版本数据长度足够，开始解析...");
                
                // 字节序转换：小端序转换（与Flutter的convertBytesEndianType一致）
                byte[] convertedData = convertBytesEndianType(versionData, 4);
                
                if (stateMachineCallback != null) {
                    StringBuilder convertedHex = new StringBuilder();
                    for (byte b : convertedData) {
                        convertedHex.append(String.format("%02X ", b));
                    }
                    stateMachineCallback.onLog("字节序转换后数据: " + convertedHex.toString());
                } else {
                    StringBuilder convertedHex = new StringBuilder();
                    for (byte b : convertedData) {
                        convertedHex.append(String.format("%02X ", b));
                    }
                    BleLog.d(TAG, "字节序转换后数据: " + convertedHex.toString());
                }
                
                // 取前2字节作为ROM版本，后2字节作为软件版本（与Flutter的sublist(0,2)和sublist(2)一致）
                byte[] romBytes = {convertedData[0], convertedData[1]};
                byte[] versionBytes = {convertedData[2], convertedData[3]};
                
                if (stateMachineCallback != null) {
                    stateMachineCallback.onLog("ROM字节: " + String.format("%02X %02X", romBytes[0], romBytes[1]));
                    stateMachineCallback.onLog("版本字节: " + String.format("%02X %02X", versionBytes[0], versionBytes[1]));
                } else {
                    BleLog.d(TAG, "ROM字节: " + String.format("%02X %02X", romBytes[0], romBytes[1]));
                    BleLog.d(TAG, "版本字节: " + String.format("%02X %02X", versionBytes[0], versionBytes[1]));
                }
                
                // 转换为十六进制字符串（与Flutter的_list2Str一致）
                String deviceRom = bytesToHexString(romBytes);
                String deviceVer = bytesToHexString(versionBytes);
                
                if (stateMachineCallback != null) {
                    stateMachineCallback.onLog("解析结果 - ROM: " + deviceRom + " (长度: " + deviceRom.length() + ")");
                    stateMachineCallback.onLog("解析结果 - 版本: " + deviceVer + " (长度: " + deviceVer.length() + ")");
                } else {
                    BleLog.d(TAG, "解析结果 - ROM: " + deviceRom + " (长度: " + deviceRom.length() + ")");
                    BleLog.d(TAG, "解析结果 - 版本: " + deviceVer + " (长度: " + deviceVer.length() + ")");
                }
                
                deviceRomVersion = deviceRom;
                deviceVersion = deviceVer;
                
                if (stateMachineCallback != null) {
                    stateMachineCallback.onLog("设备版本信息 - ROM: " + deviceRom + ", 软件版本: " + deviceVer);
                } else {
                    BleLog.d(TAG, "设备版本信息 - ROM: " + deviceRom + ", 软件版本: " + deviceVer);
                }
                
                // 保存芯片信息（与Flutter端保持一致）
                saveChipInfo(deviceRom, deviceVer);
                
                // 执行ROM版本比较
                BleLog.d(TAG, "开始执行ROM版本比较...");
                performRomCheck();
            } else {
                BleLog.w(TAG, "版本数据格式错误，长度: " + versionData.length + " (需要至少4字节)");
                if (stateMachineCallback != null) {
                    stateMachineCallback.onLog("版本数据格式错误，长度: " + versionData.length + " (需要至少4字节)");
                }
                stateMachineCallback.scheduleVersionCheckRetry(() -> performVersionCheck());
            }
        } catch (Exception e) {
            BleLog.e(TAG, "解析版本数据失败: " + e.getMessage());
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("解析版本数据异常: " + e.getMessage());
            }
            stateMachineCallback.scheduleVersionCheckRetry(() -> performVersionCheck());
        }
    }
    
    /**
     * 字节序转换：小端序转换（与Flutter的convertBytesEndianType一致）
     * @param data 原始数据
     * @param length 目标长度
     * @return 转换后的数据
     */
    private byte[] convertBytesEndianType(byte[] data, int length) {
        byte[] result = new byte[length];
        
        // 小端序转换：对于4字节数据，应该是 [b0, b1, b2, b3] -> [b3, b2, b1, b0]
        // 与Flutter的convertBytesEndianType(EndianType.littleEndian)保持一致
        for (int i = 0; i < Math.min(data.length, length); i++) {
            result[data.length - 1 - i] = data[i];
        }
        
        // 如果原始数据长度不足，用0填充
        for (int i = data.length; i < length; i++) {
            result[i] = 0;
        }
        
        return result;
    }

    private void performRomCheck() {
        changeState(OtaState.PHASE1_ROM_CHECK);
        
        try {
            // 从固件文件获取ROM版本信息
            String firmwareRom = config.getFirmwareRomVersion();
            String firmwareVersion = config.getFirmwareVersion();
            
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("=== ROM版本比较开始 ===");
                stateMachineCallback.onLog("固件版本信息 - ROM: " + firmwareRom + " (长度: " + firmwareRom.length() + "), 软件版本: " + firmwareVersion + " (长度: " + firmwareVersion.length() + ")");
                stateMachineCallback.onLog("设备版本信息 - ROM: " + deviceRomVersion + " (长度: " + deviceRomVersion.length() + "), 软件版本: " + deviceVersion + " (长度: " + deviceVersion.length() + ")");
                stateMachineCallback.onLog("固件ROM类型: " + firmwareRom.getClass().getSimpleName());
                stateMachineCallback.onLog("设备ROM类型: " + deviceRomVersion.getClass().getSimpleName());
            }
            
            // ROM版本比较（与Flutter端保持一致）
            boolean romMatch = deviceRomVersion.equals(firmwareRom);
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("ROM版本比较结果: " + romMatch);
                stateMachineCallback.onLog("设备ROM.equals(固件ROM): " + romMatch);
                stateMachineCallback.onLog("设备ROM == 固件ROM: " + (deviceRomVersion == firmwareRom));
                stateMachineCallback.onLog("设备ROM.hashCode(): " + deviceRomVersion.hashCode());
                stateMachineCallback.onLog("固件ROM.hashCode(): " + firmwareRom.hashCode());
            }
            
            if (!romMatch) {
                if (stateMachineCallback != null) {
                    stateMachineCallback.onLog("ROM版本不一致 - 设备ROM: " + deviceRomVersion + ", 固件ROM: " + firmwareRom);
                    stateMachineCallback.onLog("ROM版本比较失败，设备ROM长度: " + deviceRomVersion.length() + ", 固件ROM长度: " + firmwareRom.length());
                    stateMachineCallback.onLog("=== ROM版本比较失败 ===");
                    stateMachineCallback.onError(OtaConstants.ERROR_ROM_MISMATCH, "ROM版本不一致，无法升级");
                }
                return;
            }
            
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("ROM版本校验通过");
                stateMachineCallback.onLog("=== ROM版本比较成功 ===");
            }
            
            // 软件版本比较（可选）
            if (config.isVersionCheckEnabled()) {
                performVersionComparison(firmwareVersion);
            } else {
                if (stateMachineCallback != null) {
                    stateMachineCallback.onLog("跳过版本号校验");
                }
                performCredentialCheck();
            }
            
        } catch (Exception e) {
            BleLog.e(TAG, "ROM校验失败: " + e.getMessage());
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("ROM校验异常: " + e.getMessage());
            }
            if (stateMachineCallback != null) {
                stateMachineCallback.onError(OtaConstants.ERROR_ROM_CHECK_FAILED, "ROM校验失败: " + e.getMessage());
            }
        }
    }
    
    private void performVersionComparison(String firmwareVersion) {
        try {
            int deviceVerInt = Integer.parseInt(deviceVersion, 16);
            int firmwareVerInt = Integer.parseInt(firmwareVersion, 16);
            
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("版本比较 - 设备版本: " + deviceVerInt + ", 固件版本: " + firmwareVerInt);
            }
            
            if (deviceVerInt < firmwareVerInt) {
                if (stateMachineCallback != null) {
                    stateMachineCallback.onLog("版本校验通过，可以升级");
                }
                performCredentialCheck();
            } else {
                if (stateMachineCallback != null) {
                    stateMachineCallback.onLog("升级版本小于或等于目标设备版本号");
                    stateMachineCallback.onError(OtaConstants.ERROR_VERSION_TOO_OLD, "升级版本小于或等于目标设备版本号");
                }
            }
        } catch (NumberFormatException e) {
            BleLog.e(TAG, "版本号格式错误: " + e.getMessage());
            if (stateMachineCallback != null) {
                stateMachineCallback.onError(OtaConstants.ERROR_VERSION_FORMAT, "版本号格式错误");
            }
        }
    }
    
    private void saveChipInfo(String romVersion, String softwareVersion) {
        // 简化实现：跳过芯片信息保存，避免文件系统权限问题
        // 这个功能不是OTA升级的核心功能，可以安全跳过
        if (stateMachineCallback != null) {
            stateMachineCallback.onLog("跳过芯片信息保存，ROM=" + romVersion + ", 版本=" + softwareVersion);
        }
    }

    private void performCredentialCheck() {
        changeState(OtaState.PHASE1_CREDENTIAL_CHECK);
        if (stateMachineCallback != null) {
            stateMachineCallback.onLog("开始凭证验证，MAC码: " + macAddress + ", 授权码: " + creditCode);
        }
        
        // 启用通知，以便接收设备的凭证验证响应
        bleCommunicator.enableNotification(targetDevice, OtaProtocol.APP_OTA_SERVICE_UID, OtaProtocol.APP_OTA_NOTIFY);
        
        // 添加延迟，确保通知已启用
        stateMachineCallback.scheduleCredentialCheckRetry(new Runnable() {
            @Override
            public void run() {
                if (currentState == OtaState.PHASE1_CREDENTIAL_CHECK) {
                    if (stateMachineCallback != null) {
                        stateMachineCallback.onLog("通知已启用，开始写入凭证数据");
                    }
                    byte[] credentialData = OtaProtocol.buildCredentialData(macAddress, creditCode);
                    bleCommunicator.writeCharacteristic(targetDevice, OtaProtocol.APP_OTA_SERVICE_UID, OtaProtocol.APP_OTA_WRITE_UID, credentialData);
                }
            }
        });
    }

    private void sendUpdateCommand() {
        changeState(OtaState.PHASE1_UPGRADE_CMD);
        if (stateMachineCallback != null) {
            stateMachineCallback.onLog("发送升级命令...");
        }
        
        // *** 重要：在发送升级命令前彻底禁用自动重连 ***
        try {
            // 方法1：强制设置设备的autoConnect属性为false
            targetDevice.setAutoConnect(false);
            
            // 方法2：禁用当前设备的自动重连
            cn.com.heaton.blelibrary.ble.Ble.getInstance().autoConnect(targetDevice, false);
            
            // 方法3：清除所有自动重连设备（更彻底）
            cn.com.heaton.blelibrary.ble.queue.reconnect.DefaultReConnectHandler.provideReconnectHandler().cancelAutoConnect();
            
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("升级命令发送前已三重禁用所有自动重连");
                stateMachineCallback.onLog("设备autoConnect状态: " + targetDevice.isAutoConnect());
            }
        } catch (Exception e) {
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("禁用自动重连失败: " + e.getMessage());
            }
        }
        
        bleCommunicator.writeCharacteristic(targetDevice, OtaProtocol.APP_OTA_SERVICE_UID, OtaProtocol.APP_OTA_WRITE_UID, OtaProtocol.getUpdateCommand());
    }

    private void onUpdateCommandResult(boolean success) {
        if (success) {
            changeState(OtaState.PHASE1_DEVICE_RESTART);
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("升级命令发送成功，设备将重启到Boot模式...");
            }
            
            // 根据Flutter端的逻辑，升级命令写入成功后，设备会重启蓝牙
            // 我们需要断开连接并等待设备重新连接
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("设备重启中，断开连接并等待重新连接...");
            }
            
            // 保存当前设备信息，用于后续重新连接
            phase2Device = targetDevice;
            
            // 断开当前连接，等待设备重启后重新连接
            bleCommunicator.disconnect(targetDevice);
            
            // 第二阶段会在设备重新连接后自动开始
        } else {
            stateMachineCallback.onError(OtaConstants.ASK_STATE_UNKNOW, "发送升级命令失败");
        }
    }

    private void startDataTransfer() {
        changeState(OtaState.PHASE2_DATA_TRANSFER);
        
        if (stateMachineCallback != null) {
            stateMachineCallback.onLog("开始第二阶段数据传输...");
        }
        
        // 初始化Phase2DataManager
        try {
            // 将OtaBlock转换为Phase2DataManager需要的格式
            List<String> otaContent = convertOtaBlocksToContent(otaBlocks);
            phase2DataManager = new Phase2DataManager(targetDevice, bleCommunicator, otaContent, 
                new Phase2DataManager.Phase2DataListener() {
                    @Override
                    public void onProgressChanged(int progress, int total) {
            if (stateMachineCallback != null) {
                            stateMachineCallback.onProgressChanged(progress, total);
    }
                    }
                    
                    @Override
                    public void onLog(String message) {
        if (stateMachineCallback != null) {
                            stateMachineCallback.onLog(message);
                        }
                    }
                    
                    @Override
                    public void onError(String error) {
        if (stateMachineCallback != null) {
                            stateMachineCallback.onError(OtaConstants.ASK_STATE_UNKNOW, error);
    }
                    }
                    
                    @Override
                    public void onCompleted() {
            if (stateMachineCallback != null) {
                            stateMachineCallback.onLog("第二阶段数据传输完成");
                        }
                        completeOta();
            }
                    
                    @Override
                    public void scheduleNextBlock(Runnable runnable) {
                if (stateMachineCallback != null) {
                            stateMachineCallback.scheduleNextBlock(runnable);
                }
            }
                });
        
        if (stateMachineCallback != null) {
                stateMachineCallback.onLog("准备传输数据，总行数: " + otaContent.size());
    }
        } catch (Exception e) {
        if (stateMachineCallback != null) {
                stateMachineCallback.onError(OtaConstants.ASK_STATE_UNKNOW, "初始化数据传输失败: " + e.getMessage());
            }
            return;
    }
    
        // 开始第二阶段数据传输
        phase2DataManager.startOtaSecondStep();
    }
    
    /**
     * 发送第二阶段开始命令 [01,01,creditCode]
     */

    

    

    
    /**
     * 将OtaBlock列表转换为Phase2Protocol需要的字符串格式
     */
    private List<String> convertOtaBlocksToContent(List<OtaBlock> otaBlocks) {
        List<String> content = new ArrayList<>();
        
        if (stateMachineCallback != null) {
            stateMachineCallback.onLog("开始转换OtaBlock数据，输入块数: " + (otaBlocks != null ? otaBlocks.size() : 0));
        }
        
        if (otaBlocks == null || otaBlocks.isEmpty()) {
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("警告：OtaBlocks为空，无法转换数据");
            }
            return content;
        }
        
        for (int blockIndex = 0; blockIndex < otaBlocks.size(); blockIndex++) {
            OtaBlock block = otaBlocks.get(blockIndex);
            
            // 添加地址行（格式：@XXXXXXXX）
            String addressLine = "@" + String.format("%08X", block.address);
            content.add(addressLine);
            
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("块" + blockIndex + "地址: " + addressLine + ", 数据长度: " + block.data.length);
            }
            
            // 添加数据行（每4字节一行）
            byte[] data = block.data;
            for (int i = 0; i < data.length; i += 4) {
                StringBuilder dataLine = new StringBuilder();
                for (int j = 0; j < 4 && i + j < data.length; j++) {
                    dataLine.append(String.format("%02X", data[i + j] & 0xFF));
                }
                // 如果不足4字节，用00填充
                while (dataLine.length() < 8) {
                    dataLine.append("00");
                }
                content.add(dataLine.toString());
            }
        }
        
        if (stateMachineCallback != null) {
            stateMachineCallback.onLog("数据转换完成，总行数: " + content.size());
        }
        
        return content;
    }

    /**
     * 强制禁用设备的自动重连
     */
    private void forceDisableAutoConnect(BleDevice device) {
        try {
            // 方法1：强制设置设备的autoConnect属性为false
            device.setAutoConnect(false);
            
            // 方法2：禁用设备的自动重连
            cn.com.heaton.blelibrary.ble.Ble.getInstance().autoConnect(device, false);
            
            // 方法3：彻底清除所有自动重连设备
            cn.com.heaton.blelibrary.ble.queue.reconnect.DefaultReConnectHandler.provideReconnectHandler().cancelAutoConnect();
            
            // 方法4：强制断开设备连接，阻止任何重连尝试
            cn.com.heaton.blelibrary.ble.Ble.getInstance().disconnect(device);
            
            // 方法5：周期性清除自动重连池（最强力方法）
            startPeriodicAutoConnectCleaner();
            
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("已五重禁用设备自动重连并强制断开: " + device.getBleName());
            }
        } catch (Exception e) {
            if (stateMachineCallback != null) {
                stateMachineCallback.onLog("禁用自动重连失败: " + e.getMessage());
            }
        }
    }

    /**
     * 启动周期性自动重连清理器（最强力方法）
     */
    private void startPeriodicAutoConnectCleaner() {
        if (stateMachineCallback != null) {
            stateMachineCallback.onLog("启动强制自动重连清理器");
            
            // 使用现有的延迟机制执行多次清理
            for (int i = 0; i < 6; i++) {
                final int delay = i * 500; // 0, 500, 1000, 1500, 2000, 2500ms
                stateMachineCallback.scheduleConnectRetry(() -> {
                    try {
                        cn.com.heaton.blelibrary.ble.queue.reconnect.DefaultReConnectHandler.provideReconnectHandler().cancelAutoConnect();
                        if (stateMachineCallback != null) {
                            stateMachineCallback.onLog("执行自动重连清理，防止意外重连");
                        }
                    } catch (Exception e) {
                        // 忽略清理错误
                    }
                });
            }
        }
    }

    /**
     * 开始扫描Boot模式设备
     */
    private void startScanForBootDevice() {
        if (stateMachineCallback != null) {
            stateMachineCallback.onLog("开始自动扫描Boot模式设备，等待设备重启...");
            stateMachineCallback.onLog("注意：设备重启后可能名称变为 'ble_ota' 或使用随机MAC地址");
            
            // 显示随机MAC地址供用户识别
            String randomMac = RandomMacManager.getInstance().getRandomMacString();
            stateMachineCallback.onLog("期望随机MAC地址: " + randomMac + " (或名称为'ble_ota'的设备)");
            
            stateMachineCallback.onLog("=== 自动扫描模式 ===");
            stateMachineCallback.onLog("系统将自动扫描并连接Boot模式设备");
            stateMachineCallback.onLog("如果自动扫描失败，请手动扫描并连接Boot模式设备");
        }
        
        // 设置状态为等待Boot模式设备重连
        changeState(OtaState.PHASE2_BOOT_MODE);
        
        // 启动自动扫描Boot模式设备
        if (bootDeviceScanner != null) {
            bootDeviceScanner.startScan();
        }
    }

    // 废弃旧的传输方法
    @Deprecated
    private void transmitNextBlock() {
        throw new UnsupportedOperationException("请使用新的 transmitNextPhase2Block 方法");
    }

    @Deprecated
    private void verifyOtaData() {
        throw new UnsupportedOperationException("第二阶段验证已集成到结束命令中");
    }

    private void completeOta() {
        if (stateMachineCallback != null) {
            stateMachineCallback.onLog("=== completeOta called ===");
            stateMachineCallback.onLog("Current state before: " + currentState);
        }
        
        changeState(OtaState.COMPLETED);
        
        // 停止Boot模式设备扫描
        if (bootDeviceScanner != null) {
            bootDeviceScanner.stopScan();
        }
        
        if (stateMachineCallback != null) {
            stateMachineCallback.onLog("State changed to: " + currentState);
            stateMachineCallback.onLog("Calling onSuccess()");
        }
        
        if (stateMachineCallback != null) {
            stateMachineCallback.onSuccess();
        }
    }
}
